use anyhow::Result;
use std::collections::HashMap;
use std::path::PathBuf;
use shared::types::User;

/// 虚拟文件系统，用于管理用户权限和路径映射
pub struct VirtualFileSystem {
    user_mappings: HashMap<String, PathBuf>,
    permission_cache: HashMap<String, Vec<String>>,
}

impl VirtualFileSystem {
    pub fn new() -> Self {
        Self {
            user_mappings: HashMap::new(),
            permission_cache: HashMap::new(),
        }
    }

    /// 添加用户路径映射
    pub fn add_user_mapping(&mut self, username: &str, home_path: PathBuf) {
        self.user_mappings.insert(username.to_string(), home_path);
    }

    /// 获取用户主目录
    pub fn get_user_home(&self, username: &str) -> Option<&PathBuf> {
        self.user_mappings.get(username)
    }

    /// 检查用户是否有权限访问路径
    pub fn check_permission(&self, username: &str, path: &str) -> bool {
        if let Some(home_path) = self.user_mappings.get(username) {
            let full_path = home_path.join(path);
            full_path.starts_with(home_path)
        } else {
            false
        }
    }

    /// 规范化用户路径
    pub fn normalize_user_path(&self, username: &str, path: &str) -> Result<PathBuf> {
        if let Some(home_path) = self.user_mappings.get(username) {
            let clean_path = path.trim_start_matches('/');
            let full_path = if clean_path.is_empty() {
                home_path.clone()
            } else {
                home_path.join(clean_path)
            };

            // 确保路径在用户主目录内
            if full_path.starts_with(home_path) {
                Ok(full_path)
            } else {
                Err(anyhow::anyhow!("Path traversal detected"))
            }
        } else {
            Err(anyhow::anyhow!("User not found"))
        }
    }

    /// 缓存用户权限
    pub fn cache_user_permissions(&mut self, username: String, permissions: Vec<String>) {
        self.permission_cache.insert(username, permissions);
    }

    /// 获取缓存的用户权限
    pub fn get_cached_permissions(&self, username: &str) -> Option<&Vec<String>> {
        self.permission_cache.get(username)
    }

    /// 清除权限缓存
    pub fn clear_permission_cache(&mut self) {
        self.permission_cache.clear();
    }

    /// 移除用户映射
    pub fn remove_user_mapping(&mut self, username: &str) {
        self.user_mappings.remove(username);
        self.permission_cache.remove(username);
    }
}
